//
//  AddItemViewController.swift
//  Memorandum
//
//  Created by CurryZhang on 2019/9/23.
//  Copyright © 2019 CurryZhang. All rights reserved.
//

import UIKit
import UserNotifications

protocol AddItemViewControllerDelegate: class {
    func AddItemViewController(_ controller:AddItemViewController,endAdding item: TodoItem)
    func AddItemViewController(_ controller:AddItemViewController,endEditing item: TodoItem)
}

class AddItemViewController: UITableViewController, UITextFieldDelegate {
    weak var delegate: AddItemViewControllerDelegate?
    
    var itemToEdit: TodoItem?
    var dueDate = Date()
    var datePickerVisible = false
    
    func showDatePicker(){
        datePickerVisible = true
        
        let indexPathDatePicker = IndexPath(row: 2, section: 1)
        tableView.insertRows(at: [indexPathDatePicker], with: .fade)
    }
    
    
    @IBOutlet weak var datePicker: UIDatePicker!
    @IBOutlet weak var datePickerCell: UITableViewCell!
    @IBOutlet weak var remindSwitch: UISwitch!
    @IBOutlet weak var dueDateLabel: UILabel!
    
    @IBOutlet weak var inputTextFiled: UITextField!
    @IBOutlet weak var doneBarButton: UIBarButtonItem!
    @IBAction func cancel(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }
    
    @IBAction func commit(_ sender: Any) {
          if let item = itemToEdit {
            item.text = inputTextFiled.text!
            item.shouldRemind = remindSwitch.isOn
            item.dueDate = dueDate
            item.scheduleNotification()
            delegate?.AddItemViewController(self, endEditing: item)
          }else {
            let item = TodoItem()
            item.text = inputTextFiled.text!
            item.checked = false
            item.shouldRemind = remindSwitch.isOn
            item.dueDate = dueDate
            item.scheduleNotification()
            delegate?.AddItemViewController(self, endAdding: item)
           
        }
        
        
        dismiss(animated: true, completion: nil)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if let item = itemToEdit {
            title = "编辑备忘录"
            inputTextFiled.text = item.text
            remindSwitch.isOn = item.shouldRemind
            dueDate = item.dueDate
        }else {
            title = "新建备忘录"
        }
        updateDueDateLabel()
    }
    
    func updateDueDateLabel(){
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy年MM月dd日 HH:mm"
        dueDateLabel.text = formatter.string(from: dueDate)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        inputTextFiled.becomeFirstResponder()
    }
    
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let oldStr = textField.text! as NSString
        let newStr = oldStr.replacingCharacters(in: range, with: string)
        doneBarButton.isEnabled =  newStr.count > 0
        
        return true
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 1 && indexPath.row == 2 {
            return datePickerCell
        }else {
            return super.tableView(tableView, cellForRowAt: indexPath)
        }
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 1 && datePickerVisible {
            return 3
        }else {
            return super.tableView(tableView, numberOfRowsInSection: section)
        }
    }
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 1 && indexPath.row == 2 {
            return 217
        } else {
            return super.tableView(tableView, heightForRowAt: indexPath)
        }
    }
    
    override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
        if indexPath.section == 1 && indexPath.row == 1 {
            return indexPath
        } else {
            return nil
        }
    }
    
    override func tableView(_ tableView: UITableView, indentationLevelForRowAt indexPath: IndexPath) -> Int {
        var newIndexPath = indexPath
        if indexPath.section == 1 && indexPath.row == 2 {
            newIndexPath = IndexPath(row: 0, section: indexPath.section)
        }
        return super.tableView(tableView, indentationLevelForRowAt: newIndexPath)
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        if indexPath.section == 1 && indexPath.row == 1 {
            showDatePicker()
        }
    }

    @IBAction func dateChange(_ sender: Any) {
        dueDate = datePicker.date
        updateDueDateLabel()
    }
    @IBAction func remindToggle(_ sender: Any) {
        if remindSwitch.isOn {
            let center = UNUserNotificationCenter.current()
            center.requestAuthorization(options: [.alert, .sound]) { (_, _) in
                
            }
        }
    }
}
